<script setup lang="ts">
import { ref, Ref, reactive, toRefs } from 'vue'


interface arrtype {
  nickName: string
  message: string
}

let name = ref('')
let Message = ref('')
let arr = reactive<{
  type: String,
  id: String,
  nickname: String,
  message: String
}[]>([])

//建立连接
var ws = new WebSocket("ws://localhost:8181");
var nickname = "";
//一旦服务端响应WebSocket连接请求，就会触发open事件。响应的回调函数称为onopen
ws.onopen = function (e) {
  console.log('Connection to server opened');
}

//当消息被接收会触发消息事件，响应的回调函数叫做onmessage
ws.onmessage = function (e) {
  var data = JSON.parse(e.data);
  console.log(data);
  arr.push(data)
}
//关闭的回调
ws.onclose = function (e) {
  console.log("Connection closed", e);
}

//发送消息
function sendMessage() {
  // var messageField = document.getElementById('message');
  if (ws.readyState === WebSocket.OPEN) {
    ws.send(Message.value);
  }
  // messageField.value = '';
  // messageField.focus();
}

//修改名称
function changName() {
  // var name = $("#name").val();
  if (ws.readyState === WebSocket.OPEN) {
    ws.send("/nick " + name.value);
  }
}

/**
 * 可以多个窗口同时连接，聊天吧，注意服务的端口?
 * 目前只是看了如何连接，发送消息，如何判断用户,还有关闭，和关闭后如何自动重新连接？
 * socket.io是啥，io是啥
 * 
 */
</script>

<template>
  <div>websokect聊天室</div>
  <ul>
    <li v-for="(item, index) in arr" :key="index">
      {{ item.nickname + '-------' + item.message }}
    </li>
  </ul>
  <el-input v-model="Message" placeholder="Please Message" />
  <button @click="sendMessage">Send Message</button>
  <el-input v-model="name" placeholder="Please name" />
  <button @click="changName">Send name</button>



</template>

<style scoped>
.read-the-docs {
  color: #888;
}
</style>
